package org.example.cdpcrpbackend.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.example.cdpcrpbackend.controller.dto.Result;
import org.example.cdpcrpbackend.domain.Activity;
import org.example.cdpcrpbackend.service.ActivityService;
import org.example.cdpcrpbackend.util.CodeTool;
import org.example.cdpcrpbackend.util.QrCodeTool;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.time.LocalDateTime;

@RestController
@RequestMapping("/code")
@RequiredArgsConstructor
public class QrCodeController {
    private final ActivityService activityService;

    /**
     * QRCode-活动码-字符串
     *
     * @param id 活动id
     */
    @GetMapping("/activity/text/{id}")
    public Result getActivityCode(@PathVariable Integer id) {
        String code = CodeTool.createCode(String.valueOf(id));
        return Result.success(code);
    }


    /**
     * QRCode-活动码
     *
     * @param id 活动id
     */
    @GetMapping("/activity/{id}")
    public void createActivityCode(@PathVariable Integer id, HttpServletResponse response) {
        // 判断活动是否报名结束
        LambdaQueryWrapper<Activity> mapper = new LambdaQueryWrapper<>();
        mapper.eq(Activity::getId, id);
        mapper.gt(Activity::getEndTime, LocalDateTime.now());
        Activity activity = activityService.getOne(mapper);
        if (activity == null) {
            try {
                response.setStatus(HttpStatus.NOT_FOUND.value());
                response.setContentType(MediaType.APPLICATION_JSON_VALUE);
                response.setCharacterEncoding("UTF-8");
                Result result = Result.fail("没有当前活动，或者活动已经结束");
                String jsonResult = JSONUtil.toJsonStr(result);
                response.getWriter().write(jsonResult);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            return; // 结束本次请求【重要】
        }

        // 生成活动 code 字符串
        String code = CodeTool.createCode(String.valueOf(id));
        // 将字符串转为二维码
        BufferedImage qrCode = QrCodeTool.createQrCode(code);
        // 将 qrCode 响应给前端
        response.setContentType(MediaType.IMAGE_PNG_VALUE);
        try {
            ImageIO.write(qrCode, "png", response.getOutputStream());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * QRCode-学生校园码
     *
     * @param id 学生id
     */
    @GetMapping("/student/{id}")
    public void createStudentCode(@PathVariable String id, HttpServletResponse response) {
        if (id.length() > 30) {
            // 预防系统压力
            try {
                response.setContentType(MediaType.APPLICATION_JSON_VALUE);
                response.setCharacterEncoding("UTF-8");
                Result result = Result.fail("学号错误");
                String jsonResult = JSONUtil.toJsonStr(result);
                response.getWriter().write(jsonResult);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            return; // 结束本次请求【重要】
        }

        BufferedImage qrCode = QrCodeTool.createQrCode(id);
        response.setContentType(MediaType.IMAGE_PNG_VALUE);
        try {
            ImageIO.write(qrCode, "png", response.getOutputStream());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
